package com.fafi.selfmvc.controller;

import com.alibaba.fastjson.JSON;
import com.fafi.selfmvc.vo.MyBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.util.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;

@RestController
public class ClientController {
	static Log logger = LogFactory.getLog(ClientController.class);
	@Autowired
	private RestTemplate restTemplate;

	@RequestMapping("searchtest")
	public String searchTest() {
		String remoteUrl = "http://localhost:8080/example/one/sayHelloBystrOne?name='sdf'&&age=13";
		String result = restTemplate.getForObject(remoteUrl , String.class);

		return result;
	}

	@RequestMapping("searchSayHelloBystrThree")
	public String searchSayHelloBystrThree() {
		String remoteUrl = "http://localhost:8080/example/one/sayHelloBystrThree/name/{p1}/age/{p2}";
		String result = restTemplate.getForObject(remoteUrl , String.class,"tom",12);

		return result;
	}

	@RequestMapping("updateUserbyId")
	public String updateUserbyId() {
		String remoteUrl = "http://localhost:8080/example/user/update/{id}";
		Map<String, String> vars = Collections.singletonMap("id", "2");
		String result = restTemplate.getForObject(remoteUrl , String.class,vars);

		return result;
	}

	@RequestMapping("searchtm")
	public String searchtm() throws UnsupportedEncodingException {
		String remoteUrl = "http://localhost:8080/example/one/tm";

		/**
		 * 设置请求头
		 */
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
		headers.add("Accept", MediaType.APPLICATION_JSON.toString());

		/**
		 * POST请求参数，根据需要进行封装
		 */
		MyBean param = new MyBean();
		param.setAge(33);
		param.setName("searchtm");
		String jsonStr = JSON.toJSONString(param);
		logger.info(jsonStr.charAt(0));
		String bodyData = new String(/*Base64Util.encode(*/jsonStr/*)*/.getBytes("UTF-8"), "UTF-8");
		String jresult = "";
		for(int i = 0; i < bodyData.length(); i++) {
			jresult = jresult + bodyData.charAt(i);
		}
		logger.info(jresult);
		/**
		 * 查看HttpEntity的构造方法，包含只有请求头和只有请求体的情况
		 */
		HttpEntity<String> httpEntity = new HttpEntity<String>(bodyData, headers);

		/**
		 * 执行操作
		 */
		//String result = restTemplate.postForObject(remoteUrl, httpEntity, String.class);
		MyBean result = restTemplate.postForObject(remoteUrl, httpEntity, MyBean.class);

		//return result;
		return "success";
	}
}
